<template>
  <div class="root">
    <div class="divBox">
      <div class="content-container">
        <div class="cardBody">
          <span class="header">碳配额详情</span>
          <el-divider></el-divider>
          
          <!-- 基本信息 -->
          <img src="@/assets/icon/icon_plant.png" alt="" class="icon" />
          <span class="asset-little-title">基本信息</span>
          <div class="basic-div" style="height: 90px">
            <div class="item-div">
              <span class="item-title">签发日期</span> <br />
              <span class="item-content">{{ formatDate(tableData.issuingDate) || '--'}}</span>
            </div>
            <div class="item-div">
              <span class="item-title">签发凭证</span>
              <br /><span class="item-content" style="width: 160px; color: #126fff; cursor: pointer;
              display: inline-block; max-width: 600px;white-space:nowrap;
              overflow: hidden;text-overflow: ellipsis"
               @click="handleView(tableData.issuingCertificates)">{{  tableData.issuingCertificates || '--'   }}</span>
            </div>
            <div class="item-div">
              <span class="item-title">有效期</span> <br /><span class="item-content">{{ formatDate(tableData.expiryDate) || '--' }}</span>
            </div>
          </div>
          
          <!-- 资产信息 -->
          <br /><br />
          <img src="@/assets/icon/icon_plant.png" alt="" class="icon" />
          <span class="asset-little-title">资产信息</span>
          <div class="basic-div" style="padding: 20px 16px 20px 16px">
            <p class="paragraph">
              {{ tableData.projectIntroduction || '--' }}
            </p>
          </div>
          
          <!-- 持仓信息 -->
          <br /><br />
          <img src="@/assets/icon/icon_plant.png" alt="" class="icon" />
          <span class="asset-little-title">持仓信息</span>
          <span class="detail" @click="toDetail">查看详情<i class="el-icon-d-arrow-right"></i></span>
          <div class="basic-div" style="height: 174px">
            <div class="item-div">
              <span class="item-title">资产状态</span> <br /><span class="item-content">{{ tableData.assetsStatus || '--' }}</span>
            </div>
            <div class="item-div">
              <span class="item-title">持仓总量(tCO2e)</span> <br /><span class="item-content">{{ setNumber(tableData.total) || '--' }}</span>
            </div>
            <div class="item-div">
              <span class="item-title">资产估值(¥)</span> <br /><span class="item-content">{{ setNumber(tableData.valuation) || '--' }}</span>
            </div>
            <div class="item-div">
              <span class="item-title">可用数量(tCO2e)</span> <br /><span class="item-content">{{ setNumber(tableData.availableAmount) || '--' }}</span>
            </div>
            <div class="item-div">
              <span class="item-title">锁定数量(tCO2e)</span> <br /><span class="item-content">{{ setNumber(tableData.lockedAmount) || '--' }}</span>
            </div>
            <div class="item-div">
              <span class="item-title">冻结数量(tCO2e)</span> <br /><span class="item-content">{{ setNumber(tableData.frozenAmount) || '--' }}</span>
            </div>
          </div>
          
          <!-- 交易信息 -->
          <br /><br />
          <img src="@/assets/icon/icon_plant.png" alt="" class="icon" />
          <span class="asset-little-title">交易信息</span>
          <span class="detail" @click="toAccount">查看详情<i class="el-icon-d-arrow-right"></i></span>
          <div class="basic-div" style="height: 174px">
            <div class="item-div">
              <span class="item-title">交易状态</span> <br /><span class="item-content">{{ tableData.transactionStatus || '--' }}</span>
            </div>
            <div class="item-div">
              <span class="item-title">交割场所</span> <br /><span class="item-content">{{ tableData.carbonExchangeCode || '--' }}</span>
            </div>
            <div class="item-div">
              <span class="item-title">购入凭证</span>
              <br /><span class="item-content" style="width: 160px; color: #126fff; cursor: pointer;
              display: inline-block; max-width: 600px;white-space:nowrap;
              overflow: hidden;text-overflow: ellipsis"  @click="handleView(tableData.issuingCertificates)">
                {{ tableData.buyCertificateFileName | file || '--' }}
              </span>
            </div>
            <div class="item-div">
              <span class="item-title">购入单价(¥)</span> <br /><span class="item-content">{{ tableData.buyUnitPrice || '--' }}</span>
            </div>
            <div class="item-div">
              <span class="item-title">购入总价(¥)</span> <br /><span class="item-content">{{ tableData.buyTotalPrice || '--' }}</span>
            </div>
            <div class="item-div">
              <span class="item-title">购入日期</span> <br /><span class="item-content">{{ formatDate(tableData.buyDate) || '--' }}</span>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <br /><br />
          <div class="basic-div" style="height: 89px; background-color: white">
            <button style="width: 96px; float: right" class="light-green-btn" @click="insideTransaction">
              场内交易
            </button>
            <button style="width: 96px; float: right; margin-right: 20px" class="light-green-btn"
              @click="ousideTransaction">
              场外上架
            </button>
            <button style="width: 96px; float: right; margin-right: 20px" class="normal-white-btn" @click="goback">
              返回
            </button>
          </div>

          <!-- 场外交易弹窗 -->
          <el-dialog
  title="场外上架"
  :visible.sync="dialogFormVisible"
  width="50%"
  :close-on-click-modal="false"
  @close="resetOfflineForm"
  destroy-on-close
>
  <el-form
    ref="offlineForm"
    :model="offlineForm"
    :rules="offlineFormRules"
    label-width="160px"
  >
    <el-form-item label="出售数量(tCO2e)" prop="tradeQuantity">
      <el-input
        v-model.number="offlineForm.tradeQuantity"
        placeholder="请输入出售数量"
      ></el-input>
    </el-form-item>
    <el-form-item label="出售单价(¥)" prop="assetUnitPrice">
      <el-input
        v-model.number="offlineForm.assetUnitPrice"
        placeholder="请输入出售单价"
      ></el-input>
    </el-form-item>
    <el-form-item label="出售截止时间" prop="expirationDate">
      <el-date-picker
        v-model="offlineForm.expirationDate"
        type="date"
        placeholder="选择截止时间"
        clearable
      ></el-date-picker>
    </el-form-item>
    <el-form-item label="期望交割时间" prop="deliveryTime">
      <el-date-picker
        v-model="offlineForm.deliveryTime"
        type="date"
        placeholder="选择交割时间"
        clearable
      ></el-date-picker>
    </el-form-item>
    <!-- 期望交割方式 -->
<el-form-item label="期望交割方式" prop="deliveryMethod">
  <el-select
    v-model="offlineForm.deliveryMethod"
    placeholder="请选择"
    v-loading="optionsLoading"
  >
    <el-option
      v-for="item in deliveryMethod"
      :key="item.itemValue"
      :label="item.itemCh"
      :value="item.itemValue"
    ></el-option>
  </el-select>
</el-form-item>

<!-- 期望交割场所 -->
<el-form-item label="期望交割场所" prop="deliveryExchange">
  <el-select
    v-model="offlineForm.deliveryExchange"
    placeholder="请选择"
    v-loading="optionsLoading"
  >
   <el-option
      v-for="item in deliveryExchange"
      :key="item.itemValue"
      :label="item.itemCh"
      :value="item.itemValue"
    ></el-option>
  </el-select>
</el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button  @click="resetOfflineForm">取消</el-button>
      <el-button type="primary" @click="handleOfflineSubmit">确定</el-button>
    </span>
  </template>
</el-dialog>
          <el-dialog title="报价成功" :visible.sync="showQuotation" width="30%">
            <!-- 弹窗内容不变 -->
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { openUrlInNewWindow } from "@/libs/OpenHelper";
import { getExchangeDict } from "@/config/dictHelper";
import { getDiliveryMethodeDict } from "@/config/dictHelper";
import * as credit from "@/api/carbonAssetApi";
import { setLargeNumber } from "@/libs/public"
export default {
  name: "",
  data() {
     let Id = this.$route.query.id
    return {
      user : {},
      tableData:[],
      id : Id,
      assetDetail: [],
      Url: "https://carbonmsger.feishu.cn/drive/folder/fldcn66yo6D4OoXwZqEMHL6OQSg?from=space_persnoal_filelist",
      dialogFormVisible: false, //场外报价显示与否
      exchangeList: [],
      tradeMethods: [],
      deliveryMethod: [], // 期望交割方式列表
      deliveryExchange: [], // 期望交割场所列表
      showQuotation: false, //场外上架弹出框
      // 场外上架表单数据
      offlineForm: {
        contactsName:'',
        contactsPhone:'',
        contactsEmail:'',
        projectId: '',
        tradeQuantity: '', // 出售数量
        assetUnitPrice: '', // 出售单价
        expirationDate: null, // 出售截止时间
        deliveryTime: null, // 期望交割时间
        deliveryMethod: '', 
        deliveryExchange: '' ,
        projectScope:'',
        projectScopeCode:'',
        projectType:'',
        institutionName:''
      },
      // 场外上架表单校验规则
      offlineFormRules: {
        tradeQuantity: [
          { required: true, message: '请输入出售数量', trigger: 'blur' },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入合法数值（最多两位小数）', trigger: 'blur' }
        ],
        assetUnitPrice: [
          { required: false, message: '请输入出售单价', trigger: 'blur' },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入合法数值（最多两位小数）', trigger: 'blur' }
        ],
        expirationDate: [
          { required: false, message: '请选择出售截止时间', trigger: 'change' }
        ],
        deliveryTime: [
          { required: false, message: '请选择期望交割时间', trigger: 'change' }
        ]
      },
      optionsLoading: false,
      
      title: "",
    };
  },
  mounted() {
    this.user = JSON.parse(localStorage.getItem('user') || '{}');
    this.queryCredits();
    this.exchangeList = getExchangeDict(this.$store);
    this.tradeMethods = getDiliveryMethodeDict(this.$store);
    this.loadSelectorData();
  },
  filters: {
    file(value) {
      if (value) {
        let values = value.split("/");
        return values[values.length - 1];
      }
    },
    format(val) {
      if (!val) {
        return "--";
      }
    },
  },
  methods: {

     handleView(row) {
        const button = document.activeElement;
      // 构建百度搜索URL，将交易所名称作为搜索关键词
      const searchUrl = `${row}`;
      
      // 在新窗口打开百度搜索页面
      window.open(searchUrl, '_blank');
      if (button && button.blur) {
      // 延迟执行，确保跳转逻辑完成后再失焦
       setTimeout(() => {
      button.blur();
      // 额外措施：将焦点移到文档其他地方
      document.body.focus();
    }, 100);
      }
 },
    
     queryCredits(){
        this.$request.get('/assets/carbonQuotaAssets/queryQuotaAssets',
        { params: {
           tenantId: this.user.tenantId,
            id:this.id
         }}
        ).then(res =>{
          console.log("这是全部碳资产数据",res)
          if(res.code === 200){  
            this.tableData = res.data
            this.assetDetail = res.data; // 确保assetDetail有值
          }}
        )},

    loadSelectorData() {
      this.$request.get('/assets/carbonCreditAssets/querySelector').then(res => {
        if(res.code === 200) {  
          this.deliveryMethod = res.data.deliveryMethodList;
          this.deliveryExchange = res.data.deliveryExchangeList;
        }
      });
    },

    resetOfflineForm() {
      this.dialogFormVisible = false;
      this.offlineForm = {
        carbonProjectId: '',
        tradeQuantity: '',
        assetUnitPrice: '',
        expirationDate: null,
        deliveryTime: null,
        deliveryMethod: '',
        deliveryExchange: '',
        projectScopeCode:'',
        projectScope:'',
        projectType:'',
        institutionName:''
      };
    },

    // 提交场外上架表单
    handleOfflineSubmit() {
      this.$refs.offlineForm.validate((valid) => {
        if (valid) {
          const requestData = { ...this.offlineForm };
          this.$request.post('/trade/carbonTradeQuote/addQuota', requestData).then(res => {
            if (res.code === 200) {
              this.$message.success('场外上架提交成功');
              this.dialogFormVisible = false;
              this.queryCredits();
            } else {
              this.$message.error(res.msg || '提交失败');
            }
          }).catch(error => {
            console.error('提交失败:', error);
          });
        }
      });
    },

    setNumber(str){
      return setLargeNumber(str)
    },
    toDetail() {
      this.$router.push("/account/wallet")
    },
    // 上架成功跳转
    toQuotation() {
      this.$router.push("/trade/quotation");
    },
    toBuyFile() {
      if (this.assetDetail["buyCertificate"]) {
        openUrlInNewWindow(this.assetDetail["buyCertificate"]);
      }
    },
    toAccount(){
      openUrlInNewWindow(this.assetDetail["carbonExchangeWebsite"]);
    },
    
    formatDate(date) {
      if (date) {
        let datelist = date.split(" ");
        return datelist[0];
      }
    },
    // 场外报价按钮
    ousideTransaction() {
      this.dialogFormVisible = true;
      // 设置表单默认值
      this.offlineForm.projectId = this.assetDetail["id"] || '';
      this.offlineForm.projectType = this.assetDetail["fieldChildCode"] || '';
      this.offlineForm.institutionName = this.assetDetail["agencyName"] || '';
      this.title = "场外报价：" + (this.assetDetail["agencyName"] || '');
    },
    goback() {
      this.$router.go(-1);
    },
    insideTransaction() {
      this.$router.push("/trade/account/exchange");
    },
  },
};
</script>

<style lang="scss" scoped>
.root {
  background: #f2f5f7;
}

.divBox {
  margin: 20px;
  background: #ffffff;
  box-shadow: 0px 2px 8px 0px #eaf0f3;
  border-radius: 8px;
}

.container {
  margin: 10px 0px 20px 0px;
  display: flex;
  flex-direction: row;
}

.cardBody {
  margin: 30px 30px 30px 30px;
}

.header {
  width: 95px;
  height: 18px;
  font-size: 18px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #24a776;
  line-height: 18px;
}

.asset-title {
  width: 396px;
  height: 18px;
  font-size: 18px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #242b35;
  line-height: 18px;
  margin-left: 20px;
}

.el-divider {
  margin-top: 30px;
}

.icon {
  height: 16px;
  width: 22px;
}

.asset-little-title {
  width: 64px;
  height: 16px;
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #424c5c;
  line-height: 16px;
  margin-left: 10px;
}


.basic-div {
  width: 97%;
  height: 174px;
  background: #f7f9fc;
  border-radius: 6px;
  margin-left: 30px;
  margin-top: 30px;
}

.item-title {
  width: 56px;
  height: 14px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #5e6c84;
  line-height: 14px;
}

.item-content {
  width: 42px;
  height: 15px;
  font-size: 15px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #424c5c;
  line-height: 15px;
  position: relative;
  top: 15px;
}

.item-div {
  float: left;
  margin: 24px 45px 20px 16px;
  width: 150px;
  height: 40px;
}

.accessory {
  width: 28px;
  height: 14px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #126fff;
  line-height: 14px;
  margin-left: 10px;
}

.paragraph {
  width: 1100px;
  height: 108px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #808ea5;
  line-height: 21px;
  text-align: justify;
}

.detail {
  width: 56px;
  height: 14px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #24a776;
  line-height: 14px;
  margin-left: 15px;
  cursor: pointer;
}
</style>